package mysql.cs.command;

import common.Util.ByteUtil;
import mysql.Commond;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * 1              [15] COM_REGISTER_SLAVE
 * 4              server-id
 * 1              slaves hostname length
 * string[$len]   slaves hostname
 * 1              slaves user len
 * string[$len]   slaves user
 * 1              slaves password len
 * string[$len]   slaves password
 * 2              slaves mysql-port
 * 4              replication rank
 * 4              master-id
 */
public class RegisterSlaveCommond extends Commond {
    public long serverId;
    public String hostName;
    public String user;
    public String password;
    public int port;
    public long repRank;
    public long masterId;
    public RegisterSlaveCommond(){setCommand((byte)0x15);}

    @Override
    public void encode(byte[] data) {
        //不可能
    }

    @Override
    public byte[] decode() throws IOException {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        out.write(getCommand());
        ByteUtil.writeUnsignedIntLittleEndian(serverId, out);
        out.write((byte) hostName.getBytes().length);
        ByteUtil.writeFixedLengthBytesFromStart(hostName.getBytes(), hostName.getBytes().length, out);
        out.write((byte) user.getBytes().length);
        ByteUtil.writeFixedLengthBytesFromStart(user.getBytes(), user.getBytes().length, out);
        out.write((byte) password.getBytes().length);
        ByteUtil.writeFixedLengthBytesFromStart(password.getBytes(), password.getBytes().length, out);
        ByteUtil.writeUnsignedShortLittleEndian(port, out);
        ByteUtil.writeUnsignedIntLittleEndian(0, out);// ignored
        ByteUtil.writeUnsignedIntLittleEndian(0, out);//  -- usually 0. Appears as "master id" in SHOW SLAVE HOSTS on the master. Unknown what else it impacts.
        return out.toByteArray();
    }

    public long getServerId() {
        return serverId;
    }

    public void setServerId(long serverId) {
        this.serverId = serverId;
    }

    public String getHostName() {
        return hostName;
    }

    public void setHostName(String hostName) {
        this.hostName = hostName;
    }

    public String getUser() {
        return user;
    }

    public void setUser(String user) {
        this.user = user;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public long getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    public long getRepRank() {
        return repRank;
    }

    public void setRepRank(long repRank) {
        this.repRank = repRank;
    }

    public long getMasterId() {
        return masterId;
    }

    public void setMasterId(long masterId) {
        this.masterId = masterId;
    }
}
